package com.emuporium.gymrat.server.routine;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.emuporium.gymrat.server.data.Routine;
import com.emuporium.gymrat.server.data.RoutineDB;
import com.emuporium.gymrat.server.data.User;
import com.emuporium.gymrat.server.data.UserDB;

@SuppressWarnings("serial")
public class RoutineCreateServlet extends HttpServlet {
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String name = request.getParameter("name");
		String desc = request.getParameter("desc");
		String author = request.getParameter("author");
		Routine routine = new Routine();
		routine.setName(name);
		routine.setDescription(desc);
		routine.setAuthor(author);

		User user = UserDB.selectUser(request.getRemoteUser());

		String url = null;
		String message = "";

		if (user != null) {
			int result = RoutineDB.insert(routine, user.getId());
			if (result > 0) {

				request.setAttribute("redirecturl", "/routine/modify?id=" + result);
				url = "/includes/redirect.jsp";
				message = "Routine created, edit it below.";
				request.setAttribute("result", message);
			}
		} else {

			url = "/routine/create.jsp";
			message = "Failed to create routine";
			request.setAttribute("result", message);
		}

		RequestDispatcher dispatcher = getServletContext()
				.getRequestDispatcher(url);
		dispatcher.forward(request, response);

	}

}
